# coding=utf-8
import json
from abc import ABCMeta
import tornado.web
import WrapCursor
from CommonLib import CheckJsonKeys, CheckAuth
from database.models.DatabaseCommon import *
from database.models.PanelInstruct import PanelInstruct


class AddPanelNormal(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()

        try:
            ojson = json.loads(self.request.body)
            CheckJsonKeys(ojson, 'normalID', 'ControllerID', 'name', 'key')
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error(u'请求数据错误 :' + str(e.message)))
            return

        s = Session()
        normalID = ojson['normalID']
        cid = ojson['ControllerID']
        name = ojson['name']
        key = ojson['key']
        ps = s.query(PanelInstruct).filter_by(ControllerID=cid, Key=key).all()
        if ps is not None and len(ps) >= 1:
            self.write(r.Error(u'失败:已设置动作，请使用更新操作'))
            return
        panelIns = PanelInstruct(Name=name, NormalID=normalID, ControllerID=cid, Key=key)
        s.add(panelIns)
        try:
            s.commit()
        except Exception as e:
            self.write(r.Error(u'失败:增加面板按键动作失败'))
            return
        if panelIns.cid.TypeID != 3:
            s.delete(panelIns)
            s.commit()
            self.write(r.Error(u'控制器类型不正确'))
            return
        self.write(r.Ok(u'成功'))
        return
